﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Web.UI.DataVisualization.Charting;
using System.Data;
using HZ.Supervise.Model;
using HZ.Supervise.Model.Enum;

namespace HZ.Supervise.Web.Secondphase.Statistics
{
	public partial class StatisticsAeraBySeason : BasePage
	{
		DataTable dt = new DataTable();
		DataTable dtPie = new DataTable();
		public string AreaId;
		string year;
		string season;
		string PlanTimeFrom = "";
		string PlanTimeTo = "";
		string hname = "";

        public StatisticsAeraBySeason()
        {
            this.ModuleNo = Module.报表统计.ToString();
            this.PageOperateType = OperateType.地区季报.ToString();
        }
		protected void Page_Load(object sender, EventArgs e)
		{
			AreaId = Request["Y"];
			if (!string.IsNullOrEmpty(AreaId))
			{
				string sql = string.Format("SELECT distinct AreaName FROM TB_Area where AreaId='{0}'", AreaId);

				hname = HZ.Data.DbHelperFactory.Create().ExecuteScalar(sql).ToString();
			}

			if (!IsPostBack)
			{
				year = DateTime.Now.Year.ToString();
				//遍历dropDownList年份  by张雄 2011.4.28  modify
				foreach (ListItem item in this.droYear.Items)
				{
					//判断是不是当前年份如果是则显示当前年份
					if (item.Text == year.ToString())
					{
						item.Selected = true;
						break;
					}
				}

				GetSeason(DateTime.Now.Month.ToString());
                droSeason.Text = (int.Parse(season) - 1).ToString();
				dataBind();
                GetStatistics();
				BindMsChart();
			}

		}
		//add by 曹鹏 2011年5月12日10:42:13 根据季度拼接查询条件
		private string GetWhereBySeason(string stryear, string strSeason)
		{

			string strCondition;//储存要返回的字符串

			switch (strSeason)
			{
				case "1"://当第一个季度

					strCondition = " and daytime in (" + stryear + "01," + stryear + "02," + stryear + "03) ";

					break;

				case "2"://当第二个季度

					strCondition = " and daytime in (" + stryear + "04," + stryear + "05," + stryear + "06) ";

					break;

				case "3"://当第三个季度

					strCondition = " and daytime in (" + stryear + "07," + stryear + "08," + stryear + "09) ";

					break;

				case "4"://当第四个季度

					strCondition = " and daytime in (" + stryear + "10," + stryear + "11," + stryear + "12) ";

					break;

				default:

					strCondition = "";

					break;

			}

			return strCondition;

		}

		private void GetSeason(string i)
		{
			switch (i)
			{
				case "1":
					season = "1";

					break;
				case "2":
					season = "1";

					break;
				case "3":
					season = "1";

					break;
				case "4":
					season = "2";

					break;
				case "5":
					season = "2";

					break;

				case "6":
					season = "2";

					break;
				case "7":
					season = "3";

					break;
				case "8":
					season = "3";

					break;
				case "9":
					season = "3";

					break;
				case "10":
					season = "4";
					break;
				case "11":
					season = "4";
					break;
				case "12":
					season = "4";
					break;
			}


		}




		/// <summary>
		/// 数据绑定
		/// </summary>
		private void dataBind()
		{

			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);

			if (!string.IsNullOrEmpty(AreaId))
			{
				if (AreaId.Substring(4, 2) == "00")//市级
				{
					where += " and AreaId like '" + AreaId.Substring(0, 4) + "%'";//拼接查询条件  
				}
				else//区县
				{
					where += " and AreaId like '" + AreaId + "%'";//拼接查询条件  
				}

			}
			else//全省
			{
				where += " and AreaId like '22%' ";//拼接查询条件  
			}

			dt = ie.StatisticsAreaBySeason(where);

			HZ.Supervise.Web.Function.AddColumn(dt, "WareHouseRate");//增加新列，主要目的是格式化显示字段

			HZ.Supervise.Web.Function.ChangeRate(dt, "DistributeRate", "AddDistributeRate");
			HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate", "addDataColumnRate");

			DataTable dtGV = new DataTable();

			DataView dv = dt.DefaultView;

			dv.Sort = " daytime desc";

			dtGV = dv.ToTable();

			gvwStatisticsArea.DataSource = dtGV;

			gvwStatisticsArea.DataBind();

			//饼图取数据

			dtPie = ie.StatisticsAreaByYearPie(where);
			HZ.Supervise.Web.Function.ChangeRate(dtPie, "DistributeRate", "AddDistributeRate");
			HZ.Supervise.Web.Function.ChangeRate(dtPie, "WareHouseRate", "addDataColumnRate");
			gvwSource.DataSource = dtPie;
			gvwSource.DataBind();
            GetStatistics();
		}

		/// <summary>
		/// 绑定统计
		/// </summary>
		void GetStatistics()
		{
			double purchaseAmountTotal = 0;//采购总金额
			double DistributionAmountTotal = 0;
			double wareHouseAmountTotal = 0;//入库总金额

			for (int i = 0; i < gvwStatisticsArea.Rows.Count; i++)
			{
				purchaseAmountTotal += double.Parse(gvwStatisticsArea.Rows[i].Cells[2].Text);
				DistributionAmountTotal += double.Parse(gvwStatisticsArea.Rows[i].Cells[3].Text);
				wareHouseAmountTotal += double.Parse(gvwStatisticsArea.Rows[i].Cells[5].Text);
			}
			this.lblCount.Text = "采购总金额为:" + purchaseAmountTotal.ToString() + ";配送总金额为:" + DistributionAmountTotal.ToString() + ";入库总金额为:" + wareHouseAmountTotal.ToString();

		}

		protected void Button1_Click(object sender, EventArgs e)
		{
			year = this.droYear.SelectedValue;
			if (droSeason.SelectedValue != "-1")
			{
				season = this.droSeason.SelectedValue;
			}

			dataBind();
			BindMsChart();
		}



		/// <summary>
		/// mschart绑定
		/// by张雄  create
		/// </summary>
		private void BindMsChart()
		{

			//空为初始页
			if (dt.Rows.Count > 0)
			{
				this.divshow.Visible = true;
				string monch = "";//月份

				#region 左图
				//***********************2010基本药物******************/
                Series series3 = new Series("日常采购");
				series3.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series3.BorderWidth = 1;
				series3.ShadowOffset = 1;
				//series3.Color = Color.FromArgb(74, 172, 197);
				series3.Color = Color.FromArgb(189, 68, 104);
				series3.Label = "#VAL{F}";
				series3.ToolTip = "采购金额: #VAL{c} 万元";

				//***********************2010限价品种******************/
                Series series4 = new Series("临时采购");
				series4.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series4.BorderWidth = 1;
				series4.ShadowOffset = 1;
				series4.Color = Color.FromArgb(100, 107, 253);
				series4.Label = "#VAL{F}";
				series4.ToolTip = "配送金额: #VAL{c} 万元";

				//***********************2010补充药品******************/
                Series series5 = new Series("应急采购");
				series5.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Column", true);
				series5.BorderWidth = 1;
				series5.ShadowOffset = 1;
				series5.Color = Color.FromArgb(234, 193, 111);
				series5.Label = "#VAL{F}";
				series5.ToolTip = "入库金额: #VAL{c} 万元";
				#endregion

				#region 右图

				//**********************饼图******************/
				Series series8 = new Series("药品全年统计");
				series8.ChartType = (SeriesChartType)Enum.Parse(typeof(SeriesChartType), "Pie", true);
				series8.ToolTip = "#VALX: #VAL{c} 元";
				series8.Label = "#PERCENT{P}";
				series8.ShadowOffset = 2;
				series8.BorderColor = Color.DarkGray;
				#endregion

				#region 柱状图数据绑定
				int s = 0;//用于计数

				string str = "";//用来存储时间中月份

				//考虑去掉一个月没有数据，去掉一个月中的一条没有数据
				foreach (DataRow row in dt.Rows)
				{
					monch = HZ.Supervise.Web.Function.FormartDate(row["daytime"].ToString());//得到时间中的月份

					if (!str.Contains(monch))//如果字符串中没有该月份，也就是说该月份未被查询过
					{
						str += monch + ",";//把月份加入字符串


						series3.Points.AddXY(monch, Convert.ToDouble(row["PurchaseAmountTotal"].ToString()) / 10000);


						series4.Points.AddXY(monch, Convert.ToDouble(row["DistributeAmountTotal"].ToString()) / 10000);


						series5.Points.AddXY(monch, Convert.ToDouble(row["WarehouseAmountTotal"].ToString()) / 10000);

						s++;
					}


				}
				#endregion

				#region 饼图数据绑定



				IList<HZ.Supervise.Model.ChartModel> chartList = HZ.Supervise.DAL.DAL_Helper.CommonFillList<HZ.Supervise.Model.ChartModel>(dtPie);


				series8.Points.DataBind(chartList, "SortSource", "PurchaseAmountTotal", "LegendText=SortSource,YValues=PurchaseAmountTotal");

				//曹鹏 2011年5月23日13:19:41 判断采购类型
				for (int i = 0; i < chartList.Count; i++)
				{

                    if (chartList[i].SortSource == "日常采购")
					{

						series8.Points[i].Color = Color.FromArgb(74, 172, 197);

					}
                    else if (chartList[i].SortSource == "临时采购")
					{

						series8.Points[i].Color = Color.FromArgb(129, 101, 162);

					}
                    else if (chartList[i].SortSource == "应急采购")
					{

						series8.Points[i].Color = Color.FromArgb(192, 80, 78);

					}

				}
				#endregion

				#region 数据绑定到图

				ChartPurchasing.Series.Add(series3);
                ChartPurchasing.Series["日常采购"].ChartArea = "ChartAreaPurchasing";

				ChartPurchasing.Series.Add(series4);
                ChartPurchasing.Series["临时采购"].ChartArea = "ChartAreaPurchasing";


				ChartPurchasing.Series.Add(series5);
                ChartPurchasing.Series["应急采购"].ChartArea = "ChartAreaPurchasing";

				ChartInStorage.Series.Add(series8);

				#endregion

				#region 两张图片属性

				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisX.IsMarginVisible = true;
				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].Area3DStyle.Enable3D = false;

				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisX.MajorGrid.Interval = 0;
				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisX.LineWidth = 1;
				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisY.LineWidth = 1;

				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisY.Title = "金额（万元）";
				ChartPurchasing.ChartAreas["ChartAreaPurchasing"].AxisX.Title = "日期";
				//ChartPurchasing.ChartAreas["ChartAreaPurchasing"].Position.Auto = true;


				//ChartInStorage.ResetAutoValues();
				//ChartPurchasing.ResetAutoValues();
				#endregion

				lblnull.Visible = false;

			}
			else
			{
				this.divshow.Visible = false;
				this.ChartPurchasing.Visible = false;
				this.ChartInStorage.Visible = false;
				lblnull.Visible = true;

                this.divTable.Visible = false;
                this.btnExcel.Visible = false;
			}

		}
		/// <summary>
		/// mschat显示模式转换
		/// by张雄 2011.4.28  modify
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		protected void drpmode_SelectedIndexChanged(object sender, EventArgs e)
		{
			year = this.droYear.SelectedValue;

			season = this.droSeason.SelectedValue;
			GetSeason(season);
			dataBind();
			GetStatistics();
			BindMsChart();
		}

		protected void btnExcel_Click(object sender, EventArgs e)
		{

			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);

			if (!string.IsNullOrEmpty(AreaId))
			{
				if (AreaId.Substring(4, 2) == "00")//市级
				{
					where += " and AreaId like '" + AreaId.Substring(0, 4) + "%'";//拼接查询条件  
				}
				else//区县
				{
					where += " and AreaId like '" + AreaId + "%'";//拼接查询条件  
				}

			}
			else//全省
			{
				where += " and AreaId like '22%' ";//拼接查询条件  
			}

			dt = ie.StatisticsAreaBySeason(where);

			HZ.Supervise.Web.Function.AddColumn(dt, "WareHouseRate");//增加新列，主要目的是格式化显示字段

			HZ.Supervise.Web.Function.ChangeRate(dt, "DistributeRate", "AddDistributeRate");
			HZ.Supervise.Web.Function.ChangeRate(dt, "WareHouseRate", "addDataColumnRate");

			DataTable dtGV = new DataTable();

			DataView dv = dt.DefaultView;

			dv.Sort = " daytime desc";

			dtGV = dv.ToTable();

			HZ.Excel.ExcelHelper.ExportDataForWeb(dtGV, this.gvwStatisticsArea);


		}

		protected void btnExcel2_Click(object sender, EventArgs e)
		{
			HZ.Supervise.IBLL.IExecuteContext ie = HZ.Supervise.BLLFactory.ExecuteContext();

			string where = GetWhereBySeason(this.droYear.SelectedItem.Text, this.droSeason.SelectedItem.Text);

			if (!string.IsNullOrEmpty(AreaId))
			{
				if (AreaId.Substring(4, 2) == "00")//市级
				{
					where += " and AreaId like '" + AreaId.Substring(0, 4) + "%'";//拼接查询条件  
				}
				else//区县
				{
					where += " and AreaId like '" + AreaId + "%'";//拼接查询条件  
				}

			}
			else//全省
			{
				where += " and AreaId like '22%' ";//拼接查询条件  
			}

			dtPie = ie.StatisticsAreaByYearPie(where);
			HZ.Supervise.Web.Function.ChangeRate(dtPie, "DistributeRate", "AddDistributeRate");
			HZ.Supervise.Web.Function.ChangeRate(dtPie, "WareHouseRate", "addDataColumnRate");

			HZ.Excel.ExcelHelper.ExportDataForWeb(dtPie, this.gvwSource);
		}

		/// <summary>
		/// 地区表头
		/// by张雄  2011.5.24
		/// </summary>
		/// <param name="sender">事件发送源</param>
		/// <param name="e">事件参数</param>
		protected void gvwStatisticsArea_RowCreated(object sender, GridViewRowEventArgs e)
		{
			switch (e.Row.RowType)
			{
				case DataControlRowType.Header:

					TableCellCollection tcHeader = e.Row.Cells;
					tcHeader.Clear();

					tcHeader.Add(new TableHeaderCell());
					tcHeader[0].Attributes.Add("colspan", "8"); //跨Column
					tcHeader[0].Attributes.Add("bgcolor", "LightSteelBlue");
					SuperviseQuery sq = (SuperviseQuery)ViewState["query"];
					tcHeader[0].Text = (string.IsNullOrEmpty(hname) ? "地区汇总统计" : hname) + "</th></tr><tr>";

					//第2行表头
					tcHeader.Add(new TableHeaderCell());
					tcHeader[1].Attributes.Add("bgcolor", "Khaki");
					tcHeader[1].Text = "日期";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[2].Attributes.Add("bgcolor", "Khaki");
					tcHeader[2].Text = "采购类型";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[3].Attributes.Add("bgcolor", "Khaki");
					tcHeader[3].Text = "采购总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[4].Attributes.Add("bgcolor", "Khaki");
					tcHeader[4].Text = "配送总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[5].Attributes.Add("bgcolor", "Khaki");
					tcHeader[5].Text = "配送率";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[6].Attributes.Add("bgcolor", "Khaki");
					tcHeader[6].Text = "入库总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[7].Attributes.Add("bgcolor", "Khaki");
					tcHeader[7].Text = "入库率";

					break;
			}
		}

		protected void gvwSource_RowCreated(object sender, GridViewRowEventArgs e)
		{
			switch (e.Row.RowType)
			{
				case DataControlRowType.Header:

					TableCellCollection tcHeader = e.Row.Cells;
					tcHeader.Clear();

					tcHeader.Add(new TableHeaderCell());
					tcHeader[0].Attributes.Add("colspan", "8"); //跨Column
					tcHeader[0].Attributes.Add("bgcolor", "LightSteelBlue");
					SuperviseQuery sq = (SuperviseQuery)ViewState["query"];
					tcHeader[0].Text = (string.IsNullOrEmpty(hname) ? "地区汇总统计" : hname) + "</th></tr><tr>";

					//第2行表头
					tcHeader.Add(new TableHeaderCell());
					tcHeader[1].Attributes.Add("bgcolor", "Khaki");
					tcHeader[1].Text = "采购类型";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[2].Attributes.Add("bgcolor", "Khaki");
					tcHeader[2].Text = "采购总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[3].Attributes.Add("bgcolor", "Khaki");
					tcHeader[3].Text = "配送总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[4].Attributes.Add("bgcolor", "Khaki");
					tcHeader[4].Text = "配送率";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[5].Attributes.Add("bgcolor", "Khaki");
					tcHeader[5].Text = "入库总金额";

					tcHeader.Add(new TableHeaderCell());
					tcHeader[6].Attributes.Add("bgcolor", "Khaki");
					tcHeader[6].Text = "入库率";
					break;
			}
		}

	}
}
